<template>
    <div class="editor-page">
        <div class="container page">
            <div class="row">

            <div class="col-md-10 offset-md-1 col-xs-12">
                <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="0px">
                    <el-form-item label="" prop="title">
                        <el-input v-model="ruleForm.title" placeholder="Article Title"></el-input>
                    </el-form-item>
                    <el-form-item label="" prop="description">
                        <el-input v-model="ruleForm.description" placeholder="What's this article about?"></el-input>
                    </el-form-item>
                    <el-form-item label="" prop="body">
                        <el-input rows="8" maxlength="100" show-word-limit type="textarea" v-model="ruleForm.body" placeholder="Write your article (in markdown)"></el-input>
                    </el-form-item>
                    <el-form-item label="" prop="tagList">
                        <el-input v-model="ruleForm.tagList" placeholder="请输入标签名，以逗号分隔"></el-input>
                    </el-form-item>
                    <el-button type="primary" @click="submitForm" :loading="submitLoading">
                        {{ $route.params.slug === 'new' ? 'Publish Article' : 'Update Article'}}
                    </el-button>
                </el-form>
            </div>

            </div>
        </div>
    </div>
</template>

<script>
import { createArticle, updateArticle, getArticle } from '@/api/article'

  export default {
    name: 'Editor',
    middleware: 'authenticated',
    async asyncData ({ params }) {
        const ruleForm = {
                title: '',
                description: '',
                body: '',
                tagList: ''
            }

        if(params.slug !== 'new'){
            const { data } = await getArticle(params.slug)
            const { article } = data
            ruleForm.title = article.title
            ruleForm.description = article.description
            ruleForm.body = article.body
            ruleForm.tagList = article.tagList.join(',')
        }

        return {
            ruleForm,
            rules: {
                title: [
                    { required: true, message: '请输入标题', trigger: 'blur' }
                ],
                description: [
                    { required: true, message: '请输入描述', trigger: 'blur' }
                ],
                body: [
                    { required: true, message: '请输入内容', trigger: 'blur' }
                ],
                tagList: [
                    { required: true, message: '请输入标签名，以逗号分隔', trigger: 'blur' }
                ]
            },
            submitLoading: false
        }
    },
    methods: {
        submitForm() {
            this.$refs['ruleForm'].validate(async (valid) => {
                if (valid) {
                    this.submitLoading = true;
                    try{
                        const params = Object.assign({}, this.ruleForm)
                        params.tagList = params.tagList.split(',')
                        const { data } =  this.$route.params.slug === 'new'
                        ? await createArticle({
                            article: params
                        })
                        : await updateArticle(this.$route.params.slug, {
                            article: params
                        })
                        this.$router.push('/')
                    }catch(error) {
                        //console.dir(err)
                        let msg = ``
                        const errorObj = error.response.data.errors;
                        Object.keys(errorObj).forEach((item) => {
                            msg += `${item}：${errorObj[item][0]}<br/>`
                        })
                        this.$message({
                            type: 'error',
                            dangerouslyUseHTMLString: true,
                            message: msg
                        })
                        this.submitLoading = false;
                    }
                }
            })
        }
    }
  }
</script>